package com.gc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by Lxk on 2019/2/26.
 */

class ShareResource {

    private ReentrantLock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    private int resouce = 0;

    private int limit = 10;

    public void produce(){
        lock.lock();
        try{
            if(resouce==10){
                condition.await();
            }
            resouce++;
            System.out.println("生产了1个,当前资源池有" + resouce + "个资源");
            condition.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void consume(){
        lock.lock();
        try{
            if(resouce==0){
                condition.await();
            }
            resouce--;
            System.out.println("消费了1个，当前资源池有" + resouce + "个资源");
            condition.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}

class Producer extends Thread{
    private ShareResource shareResource;

    public Producer(ShareResource shareResource){
        this.shareResource = shareResource;
    }

    public void run(){
        while(true){
            shareResource.produce();
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Consumer extends Thread {
    private ShareResource shareResource;

    public Consumer(ShareResource shareResource){
        this.shareResource = shareResource;
    }

    public void run(){
        while(true){
            shareResource.consume();
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}


public class ReentrantLockConditionTest {


    public static void main(String[] args) throws InterruptedException {
        ShareResource shareResource = new ShareResource();
        Producer producer = new Producer(shareResource);
        Consumer consumer = new Consumer(shareResource);
        producer.start();
        consumer.start();
        Thread.sleep(1000);
    }

}
